package cn.tedu.drawn.admin.service.impl;

import cn.tedu.drawn.admin.mapper.UserMapper;
import cn.tedu.drawn.admin.pojo.dto.UserAddDTO;
import cn.tedu.drawn.admin.pojo.dto.UserChangePasswordDTO;
import cn.tedu.drawn.admin.pojo.dto.UserLoginDTO;
import cn.tedu.drawn.admin.pojo.entity.User;
import cn.tedu.drawn.admin.pojo.vo.UserListVO;
import cn.tedu.drawn.admin.pojo.vo.UserVO;
import cn.tedu.drawn.admin.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;
    @Value("${defaultPassword}")
    private String defaultPassword;


    public int login( UserLoginDTO user,
                     HttpSession session, HttpServletResponse response){
        System.out.println("user = " + user );
        UserVO u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //判断是否需要记住用户名和密码
                if (user.getRem()){
                    //通过Cookie保存用户名和密码
                    Cookie c1 = new Cookie("username",user.getUsername());
                    Cookie c2 = new Cookie("password",user.getPassword());
                    //设置保存时间
                    c1.setMaxAge(60*60*24*30);
                    c2.setMaxAge(60*60*24*30);
                    //把Cookie发送给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }

                //把当前登录成功的对象保存到Session会话里面
                session.setAttribute("user",u);
                return 1;
            }
            return 3;
        }
        return 2;
    }

    @Override
    public void changePassword(UserChangePasswordDTO userChangePasswordDto) {
        System.out.println("userChangePasswordDto"+userChangePasswordDto);
        mapper.changePassword(userChangePasswordDto);
    }

    @Override
    public List<UserListVO> select() {
        return mapper.select();
    }

    @Override
    public void insert(UserAddDTO userAddDTO) {
        User user = new User();
        BeanUtils.copyProperties(userAddDTO,user);
        mapper.insert(user);
    }

    @Override
    public void defaultPassword(String id) {
        UserChangePasswordDTO userChangePasswordDto = new UserChangePasswordDTO();
        userChangePasswordDto.setPassword(defaultPassword);
        userChangePasswordDto.setId(id);
        mapper.changePassword(userChangePasswordDto);
    }

    @Override
    public void delete(int id) {
        mapper.deleteById(id);
    }


}
